﻿using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Collections;


using BEX.Core;

namespace BEX.Core.Exchange.BITFINEX
{
    public class Bitfinex : Exchange
    {
        public Bitfinex()
            : base(ExchangeType.BITFINEX)
        {

        }

        internal override Tick GetCurrentTick(CurrencyPair pair)
        {

            BitfinexResponse _response = GetBitfinexTick(pair);

            Tick res = new Tick();


            res.Ask = Convert.ToInt32(Convert.ToDecimal(_response.ask) * global.ConversionFactor);
            res.Bid = Convert.ToInt32(Convert.ToDecimal(_response.bid) * global.ConversionFactor);
            res.Currency = pair;
            res.ExchangeSource = ExchangeType.BITFINEX;
            res.Time = DateTime.UtcNow;
            res.Spot = Convert.ToInt32(Convert.ToDecimal(_response.last_price) * global.ConversionFactor);

            return res;
        }

        private BitfinexResponse GetBitfinexTick(CurrencyPair pair)
        {
            //https://bitfinex.com/api/v1/ticker/{0}{1}
            var queryStr = string.Format(TickerURL, pair.Base.ToString().ToLower(), pair.Counter.ToString().ToLower());

            var resp = Query(queryStr);

            return new BitfinexResponse(JObject.Parse(resp));
        }

        private static string Query(string url)
        {
           
            var request = WebRequest.Create(url);
            request.Method = "GET";
            if (request == null)
            {
                throw new Exception("Non HTTP WebRequest");
            }
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }

        protected override string _baseUrl
        {
            get { return ExchangeConfig.Default.BitfinexAPI_BaseURL; }
        }

        protected override string _tickPath
        {
            get { return ExchangeConfig.Default.BitfinexAPI_GetTickPath; }
        }

        protected override string _pairs
        {
            get { return ExchangeConfig.Default.Bitfinex_Pairs; }
        }
    }
}
